package com.sann.demo.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 获取数据库连接的一个工具类，它用于从数据源中获取一个连接，并且实现和线程的绑定
 */
@Component
public class ConnectionUtil {
    private ThreadLocal<Connection> tl = new ThreadLocal<>();

    @Autowired
    DataSource dataSource;

    /**
     * 获取当前线程上绑定的Connection
     */
    public Connection getThreadConnection(){
        try {
            //1.尝试从ThreadLocal 上获取Connection
            Connection connection = tl.get();
            //2.判断当前线程上是否有Connection
            if(connection == null){
                //3.从数据源中获取一个连接，并且存入ThreadLocal中
                connection = dataSource.getConnection();
                //4.让 ThreadLocal 保存一份
                tl.set(connection);
            }
            //5.返回当前线程上的Connection
            return connection;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void removeConnection(){
        tl.remove();
    }

}
